﻿using LdtDataEngin.ModuleDetail.BaseModule.Optimization;
using LdtDataEngin.ModuleDetail.CaseCauseElementOpt;
using LdtDataEngin.ModuleDetail.CaseElmentOpt;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.CommHelp;
using LdtJudge.DataEngine.Common.DataSave;
using LdtJudge.DataEngine.Common.XmlUtility;
using LdtJudge.DataEngine.Data.DataParseStorage;
using LdtJudge.DataEngine.Model.CommModel;
using LdtJudge.DataEngine.Model.DataModel;
using LdtJudge.DataEngine.Model.DataModel.DataParseStorage;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using System.Xml;

namespace LdtDataEngin.ModuleDetail.OptimizationModule.FillBackOptimization
{
    public class FillBackOptimization : OptimizationBase
    {
        #region 字段信息
        /// <summary>
        /// 回填内容  xml格式
        /// 调用时传入
        /// </summary>
        public string OptimizationXmlContent { get; set; }
        /// <summary>
        /// xml文件存放路径dynamicDataStores.dataLayerStores.AnalysisParameter.sourceDossierInfo.SD_ElementPath
        /// </summary>
        public string XmlFileDirectory { get; set; }
        /// <summary>
        /// 案件唯一ID
        /// 调用时传入
        /// </summary>
        public string CaseOnlyID { get; set; }
        /// <summary>
        /// 应用code 对应配置文件中的数据源
        /// 调用时传入
        /// </summary>
        public string AppCode { get; set; }
        /// <summary>
        /// 优选结果XML
        /// </summary>
        public XmlDocument OptimizationResult { get; set; }
        /// <summary>
        /// 数据源(历史数据)XML
        /// </summary>
        public List<DataModel> SourceDataModelList { get; set; }

        /// <summary>
        /// 案件要素内容
        /// </summary>
        public string Casexmlcontst { get; set; }

        /// <summary>
        /// 案由要素内容
        /// </summary>
        public string Elementxmlcontst { get; set; }

        /// <summary>
        /// xml操作类
        /// </summary>
        private XmlUtilCommon xmlUtilCommon { get; set; }
        #endregion

        public FillBackOptimization()
        {

        }

        /// <summary>
        /// 案件回填
        /// </summary>
        /// <param name="xmlContext">回填内容</param>
        public void BackOptimization(string xmlContext)
        {
            OptimizationConfig(Casexmlcontst);
            OptimizationElementConfig(Elementxmlcontst);

            string messages = HttpHelp.DeCodeBase64new(65001, xmlContext.Replace('"', ' ')).Replace("&lt;", "<").Replace("&gt;", ">");
            dynamic dys = JsonConvert.DeserializeObject<dynamic>(messages);
            string ff = dys.changedata.ToString();
            List<ChangeDataModel> changeDataModelList = JsonConvert.DeserializeObject<List<ChangeDataModel>>(ff);

            List<An_anjianxinxi> an_Anjianxinxis = new List<An_anjianxinxi>();
            DAL_An_anjianxinxi dAL_An_Anjianxinxi = new DAL_An_anjianxinxi();
            an_Anjianxinxis = dAL_An_Anjianxinxi.GetList(dataContext.DataLayerAns.CaseId);

            List<An_anjiancunchu> an_Anjiancunchus = new List<An_anjiancunchu>();
            DAL_An_anjiancunchu dAL_An_Anjiancunchu = new DAL_An_anjiancunchu();
            an_Anjiancunchus = dAL_An_Anjiancunchu.GetList(dataContext.DataLayerAns.CaseId);

            DataResultSave dataResultSave = new DataResultSave(dataContext);
            xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };
            if (an_Anjianxinxis.Count > 0)
            {
                if (dataContext.DataLayerAns.FengXiCanShu == null)
                {
                    dataContext.DataLayerAns.FengXiCanShu = new An_fengxicanshu();
                }
                dataContext.DataLayerAns.CaseId = an_Anjianxinxis.First().Anjianid;
                //dataContext.DataLayerAns.case = an_Anjianxinxis.First().Anhao;
                //dataContext.DataLayerAns.FengXiCanShu. = an_Anjianxinxis.First().Anjianid;
                dataContext.DataLayerAns.FengXiCanShu.Fayuanid = an_Anjianxinxis.First().Fayuanid;

                if (an_Anjiancunchus.Where(a=>a.Cunchuleixing=="3") != null)
                {
                    string xmlID = an_Anjiancunchus.Where(a => a.Cunchuleixing == "3")?.First().Wenjianid;
                    XmlDocument xmlDataSours = dataResultSave.ReadDataXML(xmlID);
                    SourceDataModelList = XmlUtility.DeserializeToObject<DataSoursModel>(xmlDataSours.OuterXml).dataModelList;
                }
            }
            foreach (ChangeDataModel changeDataModel in changeDataModelList)
            {
                switch (changeDataModel.ChangeType.ToLower())
                {
                    case "a_attr":
                        //新增属性
                        A_attrClass(changeDataModel);
                        break;
                    case "a_node":
                        //新增节点
                        A_nodeClass(changeDataModel);
                        break;
                    case "m_attr":
                        //修改属性
                        A_attrClass(changeDataModel);
                        break;
                    case "d_attr":
                        //删除属性
                        D_attrClass(changeDataModel);
                        break;
                    case "d_node":
                        //删除节点
                        D_nodeClass(changeDataModel);
                        break;
                }
            }
            SaveXml(dataResultSave);
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="dataResultSave">数据保存对象</param>
        private void SaveXml(DataResultSave dataResultSave) 
        {
            dataContext.DataLayerOpt.OptimizationXml = xmlUtilCommon.DataModelByXml(SourceDataModelList, "");
            XmlDocument dataSourXML = new XmlDocument();
            DataSoursModel dataSoursModel = new DataSoursModel();
            dataSoursModel.dataModelList = SourceDataModelList;
            dataSourXML.LoadXml(XmlUtility.SerializeToXml<DataSoursModel>(dataSoursModel));
            //dataContext.DataLayerOpt.SourdataXml = dataSourXML;
            dataContext.DataLayerOpt.SourdatModleList = SourceDataModelList;
            //保存优选的数据
            dataResultSave.OptimizationSave();
        }

        /// <summary>
        /// 对属性进行添加
        /// </summary>
        /// <param name="changeDataModel"></param>
        private void A_attrClass(ChangeDataModel changeDataModel)
        {
            string attName = changeDataModel.ChangeAttrName.Trim();
            string attValue = HttpHelp.DeCodeBase64new(65001, changeDataModel.ChangeValue.Trim());
            if (!string.IsNullOrEmpty(attName) && !string.IsNullOrEmpty(attValue) && !string.IsNullOrEmpty(changeDataModel.NodeId))
            {
                dataContext.InteractiveShow.LogShow("进入属性添加,属性值:" + attValue);
                DataModel dataModelRoot = SourceDataModelList.FirstOrDefault(a => a.ID == changeDataModel.NodeId);
                dataContext.InteractiveShow.LogShow("进入属性添加,节点值:" + JsonConvert.SerializeObject(dataModelRoot));
                if (dataModelRoot != null)
                {
                    List<Sourcedata> sourceDatade = new List<Sourcedata>();
                    List<Xmllable> xmllableList = new List<Xmllable>();
                    //属性值
                    AttributeInfo attribute = dataModelRoot.AttributesList.FirstOrDefault(a => a.Name == attName);

                    Source source = new Source();
                    source.SaveValue = attValue;
                    source.SourceCode = dataContext.DataLayerAns.SourceCode;

                    if (attribute == null)
                    {
                        source.IsCheck = "1";
                        attribute = new AttributeInfo();
                        attribute.Name = attName;
                        attribute.sourceList = new List<Source>();
                        attribute.sourceList.Add(source);
                        dataModelRoot.AttributesList.Add(attribute);
                    }
                    else
                    {
                        if (dataModelRoot.XmlPath.IndexOf("案由要素") == -1)
                        {
                            sourceDatade = OptimizConfig.Sourcedatadefine[0].SourcedataList;
                            xmllableList = OptimizConfig.XmllableList;
                        }
                        else
                        {
                            sourceDatade = OptimizeElement.Sourcedatadefine[0].SourcedataList;
                            xmllableList = OptimizeElement.CaseTypeList[0].XmlFactTypeList[0].XmllableList;
                        }

                        if (sourceDatade != null)
                        {
                            Sourcedata sourcedataop = sourceDatade.FirstOrDefault(a => a.Code.ToLower() == attribute.sourceList.FirstOrDefault(b => b.IsCheck == "1").SourceCode.ToLower());
                            Sourcedata sourcedataas = sourceDatade.FirstOrDefault(a => a.Code.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower());
                            Xmllable xmllable = xmllableList.FirstOrDefault(a => a.Xmlpath == dataModelRoot.XmlPath);
                            int assum = ListByCount(xmllable.Priority.Split('>').ToList(), sourcedataas.id.ToString());
                            if (sourcedataop != null )
                            {
                                int opsum = ListByCount(xmllable.Priority.Split('>').ToList(), sourcedataop.id.ToString());
                                if (attribute.sourceList.FirstOrDefault(a => a.SourceCode == dataContext.DataLayerAns.SourceCode) != null)
                                {
                                    attribute.sourceList.FirstOrDefault(a => a.SourceCode == dataContext.DataLayerAns.SourceCode).SaveValue = attValue;
                                    dataContext.InteractiveShow.LogShow("当前数据源序号" + assum + "::" + opsum);
                                    if (assum <= opsum)
                                    {
                                        for (int i = 0; i < attribute.sourceList.Count; i++)
                                        {
                                            attribute.sourceList[i].IsCheck = "0";
                                        }
                                        attribute.sourceList.FirstOrDefault(a => a.SourceCode == dataContext.DataLayerAns.SourceCode).IsCheck = "1";
                                    }
                                }
                                else
                                {
                                    dataContext.InteractiveShow.LogShow("当前数据源序号" + assum + "::" + opsum);
                                    if (assum <= opsum)
                                    {
                                        for (int i = 0; i < attribute.sourceList.Count; i++)
                                        {
                                            attribute.sourceList[i].IsCheck = "0";
                                        }
                                        source.IsCheck = "1";
                                    }
                                    else
                                    {
                                        source.IsCheck = "0";
                                    }
                                    attribute.sourceList.Add(source);
                                }
                            }
                            else
                            {
                                if (attribute.sourceList.FirstOrDefault(a => a.SourceCode == dataContext.DataLayerAns.SourceCode) != null)
                                {
                                    attribute.sourceList.FirstOrDefault(a => a.SourceCode == dataContext.DataLayerAns.SourceCode).SaveValue = attValue;
                                }
                                else
                                {
                                    if (assum!=99)
                                    {
                                        for (int i = 0; i < attribute.sourceList.Count; i++)
                                        {
                                            attribute.sourceList[i].IsCheck = "0";
                                        }
                                        source.IsCheck = "1";
                                    }
                                    else
                                    {
                                        source.IsCheck = "0";
                                       
                                    }
                                    attribute.sourceList.Add(source);
                                }
                              
                            }

                        }
                    }
                }
            }
        }

        /// <summary>
        /// 对节点进行添加
        /// </summary>
        /// <param name="changeDataModel"></param>
        private void A_nodeClass(ChangeDataModel changeDataModel)
        {
            //string nodeValue = HttpHelp.DeCodeBase64new(65001, changeDataModel.ChangeValue.Trim());
            //string nodeID = changeDataModel.NodeId.Trim();
            //List<DataModel> dataModelListOP = new List<DataModel>();
            //XmlDocument nodeDocument = new XmlDocument();
            //nodeDocument.LoadXml(nodeValue);
            //DataSoursModel dataSoursModel = xmlUtilCommon.GetXMLByDataModelBackFill(nodeDocument);
            //if (nodeID=="0")
            //{
            //    FormatDataSource formatDataSource = new FormatDataSource(dataContext);
            //    formatDataSource.FromatNodeListAsiss(dataSoursModel.dataModelList);
            //    OptimizationNew optimizationNew = new OptimizationNew();
            //    dataLayerStores.AnalysisResultsDataModel = new DataSoursModel();
            //    dataLayerStores.AnalysisResultsDataModel.dataModelList = dataSoursModel.dataModelList;
            //    optimizationNew.dataLayerStores = dataLayerStores;
            //    optimizationNew.InteractiveShow = InteractiveShow;
            //    optimizationNew.OptimizConfig = OptimizConfig;
            //    optimizationNew.OptimizeElement = OptimizeElement;
            //    optimizationNew.Casexmlcontst = Casexmlcontst;
            //    optimizationNew.Elementxmlcontst = Elementxmlcontst;
            //    AnalysisDataControl analysisDataControl = new AnalysisDataControl(GetDynamic());
            //    //保存分析数据
            //    AnalysisParameterModel analysisParameters = analysisDataControl.SaveData(3);
            //    optimizationNew.CarryOutOptimization();
            //    SourceDataModelList= optimizationNew.dataLayerStores.SourdatModleList;

            //}
            //else
            //{
            //    DataModel dataModelRoot = SourceDataModelList.FirstOrDefault(a => a.ID == nodeID);
            //    if (dataSoursModel != null && dataModelRoot != null)
            //    {
            //        List<Sourcedata> sourceDatade = null;
            //        List<Xmllable> xmllableList = null;
            //        if (dataModelRoot.XmlPath.IndexOf("案由要素") == -1)
            //        {
            //            sourceDatade = OptimizConfig.Sourcedatadefine[0].SourcedataList;
            //            xmllableList = OptimizConfig.XmllableList;
            //        }
            //        else
            //        {
            //            sourceDatade = OptimizeElement.Sourcedatadefine[0].SourcedataList;
            //            xmllableList = OptimizeElement.CaseTypeList[0].XmlFactTypeList[0].XmllableList;
            //        }
            //        dataModelListOP = xmlUtilCommon.SubordinateDataModelList(SourceDataModelList, dataModelRoot);
            //        dataSoursModel.dataModelList.FirstOrDefault(a => a.ParentId == "").ParentId = dataModelRoot.ID;
            //        if (dataModelListOP.Count == 1)
            //        {
            //            SourceDataModelList.AddRange(dataSoursModel.dataModelList);
            //        }
            //        else
            //        {
            //            OptimizationNew optimizationNew = new OptimizationNew();
            //            optimizationNew.dataLayerStores = dataLayerStores;
            //            optimizationNew.InteractiveShow = InteractiveShow;
            //            foreach (DataModel mode in dataSoursModel.dataModelList)
            //            {
            //                mode.XmlPath = dataModelRoot.XmlPath +"/"+ mode.XmlPath;
            //            }
            //            optimizationNew.OptimizConfig = OptimizConfig;
            //            optimizationNew.OptimizeElement = OptimizeElement;
            //            optimizationNew.CaseElmentOptimization(dataSoursModel.dataModelList, dataModelRoot.ID, SourceDataModelList);
            //        }
            //    }
            //}
            
        }
        /// <summary>
        /// 对属性进行删除
        /// </summary>
        /// <param name="changeDataModel"></param>
        private void D_attrClass(ChangeDataModel changeDataModel)
        {
            string attName = changeDataModel.ChangeAttrName.Trim();
            string attValue = "";
            if (!string.IsNullOrEmpty(attName) && !string.IsNullOrEmpty(changeDataModel.NodeId))
            {
                DataModel dataModelRoot = SourceDataModelList.FirstOrDefault(a => a.ID == changeDataModel.NodeId);
                if (dataModelRoot != null)
                {
                    List<Sourcedata> sourceDatade = new List<Sourcedata>();
                    List<Xmllable> xmllableList = new List<Xmllable>();
                    //属性值
                    AttributeInfo attribute = dataModelRoot.AttributesList.FirstOrDefault(a => a.Name == attName);

                    Source source = new Source();
                    source.SaveValue = attValue;
                    source.SourceCode = dataContext.DataLayerAns.SourceCode;

                    if (attribute == null)
                    {
                        source.IsCheck = "1";
                        attribute = new AttributeInfo();
                        attribute.Name = attName;
                        attribute.sourceList.Add(source);
                        dataModelRoot.AttributesList.Add(attribute);
                    }
                    else
                    {
                        if (dataModelRoot.XmlPath.IndexOf("案由要素") == -1)
                        {
                            sourceDatade = OptimizConfig.Sourcedatadefine[0].SourcedataList;
                            xmllableList = OptimizConfig.XmllableList;
                        }
                        else
                        {
                            sourceDatade = OptimizeElement.Sourcedatadefine[0].SourcedataList;
                            xmllableList = OptimizeElement.CaseTypeList[0].XmlFactTypeList[0].XmllableList;
                        }

                        if (sourceDatade != null)
                        {
                            Sourcedata sourcedataop = sourceDatade.FirstOrDefault(a => a.Code.ToLower() == attribute.sourceList.FirstOrDefault(b => b.IsCheck == "1").SourceCode.ToLower());
                            Sourcedata sourcedataas = sourceDatade.FirstOrDefault(a => a.Code.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower());
                            if (sourcedataop != null && sourcedataas != null)
                            {
                                Xmllable xmllable = xmllableList.FirstOrDefault(a => a.Xmlpath == dataModelRoot.XmlPath);
                                int opsum = ListByCount(xmllable.Priority.Split('>').ToList(), sourcedataop.id.ToString());
                                int assum = ListByCount(xmllable.Priority.Split('>').ToList(), sourcedataas.id.ToString());
                                if (attribute.sourceList.FirstOrDefault(a => a.SourceCode == dataContext.DataLayerAns.SourceCode) != null)
                                {
                                    foreach (Source sources in attribute.sourceList)
                                    {
                                        source.IsCheck = "0";
                                    }
                                    attribute.sourceList.FirstOrDefault(a => a.SourceCode == dataContext.DataLayerAns.SourceCode).SaveValue = attValue;
                                    if (assum <= opsum)
                                    {
                                        attribute.sourceList.FirstOrDefault(a => a.SourceCode == dataContext.DataLayerAns.SourceCode).IsCheck = "1";
                                    }
                                }
                                else
                                {
                                    if (assum <= opsum)
                                    {
                                        source.IsCheck = "1";
                                    }
                                    else
                                    {
                                        source.IsCheck = "0";
                                    }
                                    attribute.sourceList.Add(source);
                                }
                            }
                            else
                            {
                                if (attribute.sourceList.FirstOrDefault(a => a.SourceCode == dataContext.DataLayerAns.SourceCode) != null)
                                {
                                    attribute.sourceList.FirstOrDefault(a => a.SourceCode == dataContext.DataLayerAns.SourceCode).SaveValue = attValue;
                                }
                                else
                                {
                                    source.IsCheck = "1";
                                    attribute.sourceList.Add(source);
                                }
                            }

                        }
                    }
                }
            }
        }
        /// <summary>
        /// 对节点进行删除
        /// </summary>
        /// <param name="changeDataModel"></param>
        private void D_nodeClass(ChangeDataModel changeDataModel)
        {
            string nodeID = changeDataModel.NodeId;
            DataModel dataModelRoot = SourceDataModelList.FirstOrDefault(a => a.ID == nodeID);
            if (dataModelRoot != null)
            {
                List<DataModel> dataModelList = xmlUtilCommon.SubordinateDataModelList(SourceDataModelList, dataModelRoot);
                foreach (DataModel mode in dataModelList)
                {
                    SourceDataModelList.Remove(mode);
                }
            }
        }
    }
}
